package com.cloudfast.email.impl;

import javax.mail.internet.MimeMessage;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.cloudfast.config.EmailAuth;
import com.cloudfast.email.JEmailSender;
import com.cloudfast.email.text.EmailMessage;

/**
 * 发送邮箱实现类
 *
 * @author liuyw
 * @date 2022-10-22
 */
public class JEmailSenderImpl implements JEmailSender {

    private JavaMailSender javaMailSender;

    private EmailAuth emailAuth;

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    public JEmailSenderImpl(EmailAuth emailAuth, JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
        this.emailAuth = emailAuth;
    }

    @Override
    public boolean sendTextMail(EmailMessage emailMessage) {
        try {
            // 创建邮件内容
            SimpleMailMessage message = new SimpleMailMessage();
            // 这里指的是发送者的账号
            message.setFrom(emailAuth.getUsername());
            message.setTo(emailMessage.getRevUser().split(","));
            if (StringUtils.isNotEmpty(emailMessage.getCcUser())) {
                message.setCc(emailMessage.getCcUser().split(","));
            }
            if (StringUtils.isNotEmpty(emailMessage.getTitle())) {
                message.setSubject(emailMessage.getTitle());
            }
            if (StringUtils.isNotEmpty(emailMessage.getContent())) {
                message.setText(emailMessage.getContent());
            }
            // 发送邮件
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return false;
    }

    @Override
    public boolean sendHtmlMail(EmailMessage emailMessage) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            // 创建邮件内容 true 表示创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailAuth.getUsername());
            helper.setSubject(emailMessage.getTitle());
            if (StringUtils.isNotEmpty(emailMessage.getCcUser())) {
                helper.setCc(emailMessage.getCcUser().split(","));
            }
            if (StringUtils.isNotEmpty(emailMessage.getTitle())) {
                helper.setSubject(emailMessage.getTitle());
            }
            if (StringUtils.isNotEmpty(emailMessage.getContent())) {
                helper.setText(emailMessage.getContent(), true);
            }
            // 发送邮件
            javaMailSender.send(message);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return false;
    }

}
